__author__="jregent"
__date__ ="$17.12.2008 16:41:12$"

import os
import sys
import logging

# Allow us to run using installed `libgmail` or the one in parent directory.
try:
    import libgmail
    #logging.warn("Note: Using currently installed `libgmail` version.")
except ImportError:
    # Urghhh...
    sys.path.insert(1,
    os.path.realpath(os.path.join(os.path.dirname(__file__),
    os.path.pardir)))

#import libgmail





subject = "gmail_DL test sendMail+labels"
content = """GreyBox 3 is released :)

The new version features...

Check out http://orangoo.com/labs/GreyBox/ for more information.

Kind regards,
4mir Salihefendic (http://amix.dk)"""
class Gmail_DL:
    def __init__( self, user = "", pw = ""):
        global ga, gaLoggedIn, gaErrorMessage
        """
        """
        gaResult = gaLoggedIn = False
        gaErrorMessage = ''
        if not user:
            gaErrorMessage = 'Error: User name is missing.'
            return
        if not pw:
            gaErrorMessage = 'Error: Password name is missing.'
            return
        ga = libgmail.GmailAccount(user, pw)
        try:
            ga.login()
            gaLoggedIn = True
        except libgmail.GmailLoginFailure,e:
            gaErrorMessage = "Error: " + e.message
            gaLoggedIn = False

    def loggedIn(self):
        return gaLoggedIn

    def errorMessage(self):
        return gaErrorMessage

    def archiveMessage(self, thread):
        gaErrorMessage = ''
        ARCHIVE_ACTION='rc_^i' #the action string to archive a message
        try:
            ga._doThreadAction(ARCHIVE_ACTION, thread)
            return True
        except libgmail.GmailSendError,e:
            gaErrorMessage = "Error: " + e.message
            return False

    def sendEmail(self, to_email, subject, content, labels_commaSeparated ):
        if not gaLoggedIn:           return
        gaErrorMessage = ''
        gmsg = libgmail.GmailComposedMessage(to_email, subject, content)
        try:
            result = ga.sendMessage(gmsg)
            if result:
                addLabels(result, labels_commaSeparated)
                return True
        except libgmail.GmailSendError,e:
            gaErrorMessage = "Error: " + e.message
            return False
        return False

    def sendEmail_test(self):
        if not gaLoggedIn:           return
        print "gmail_DL test start"
        testLabels = "zTest.1, zTest.2, zTest.3"
        sendEmail('jan.regent@gmail.com',subject, content, testLabels)
        print "gmail_DL test end"

    def addLabels(self, messageObj, labels_commaSeparated ) :
        if not gaLoggedIn:           return
        gaErrorMessage = ''
        if messageObj:
            try:
                labels = labels_commaSeparated.split(',')
                for label in labels: messageObj.addLabel(label)
                return True
            except libgmail.GmailError,e:
                gaErrorMessage = "Error: " + e.message
                return False
        return False


    def getLabelNames(self):
        if not gaLoggedIn:           return
        gaErrorMessage = ''
        try:
            labels = ga.getLabelNames()
        except libgmail.GmailError,e:
            gaErrorMessage = "Error: " + e.message
            return None
        return None

    def getLabelNames_test(self):
        labels = ga.getLabelNames()
        if labels:
            for label in labels: print label.encode("utf-7")
            return labels

    def query(self, query_string):
        if not gaLoggedIn:           return
        #qrystr = 'label:backup label:z-ac#'
        #qrystr = "kwd: after:2008/07/10"
        #qrystr = "kwd: "
        try:
            return ga.getMessagesByQuery(query_string, True)
        except libgmail.GmailError,e:
            gaErrorMessage = "Error: " + e.message
            return None


    def query2html(self, query_string):
        link = '<a href="http://mail.google.com/mail/\
    ?fs=1&tf=1&source=atom&view=cv&search=all\
    &th=%(id)s&shva=1">%(subject)s</a>'

        messages =  query(query_string)
        if messages:
            for thread in messages:
                #if len(thread) == 1:
                if thread:
                    d = {'id': thread.id, 'subject': thread.subject.encode("utf-7")}
                    print '<p>%s</p>' % (link % d)
                    addLabels(thread,"zTest.1, zTest.2, zTest.3")

    def storeFile(self, filename, label):
        if not gaLoggedIn: return False
        gaErrorMessage = ''
        try:
            if ga.storeFile(filename, label=label):
                return True
        except libgmail.GmailError,e:
            gaErrorMessage = "Error: " + e.message
            return False
        return False
    
##for l in open("emails"):
##  email, author = l.split(", ")
##  sendEmail(email)



if __name__ == "__main__":
    user = "jan.regent@gmail.com"
    pasw = "kamdom"
    gm = Gmail_DL(user, pasw)
    #sendEmail_test()
    #query("label:backup label:z-ac#")
    #query("label:backup label:z-ac#")
    #query("label:py label:hosting")
    #query("is:unread")
    #qrystr = 'label:backup label:z-ac#'
    #qrystr = "kwd: after:2008/07/10"

    link = '<a href="http://mail.google.com/mail/\?fs=1&tf=1&source=atom&view=cv&search=all\&th=%(id)s&shva=1">%(subject)s</a>'
    mess_by_id_link = "http://mail.google.com/mail?account_id=jan.regent@gmail.com&message_id=__id__&view=conv&extsrc=atom"
    gmail_query_string = "kwd: after:2009/01/06 before:2009/01/07"
    messages = gm.query(gmail_query_string)
    fileHandle = open ( 'c:\gm_mess.xml', 'w' )
    fileHandle.write ( "<gmail_query>" )
    fileHandle.write ( "<gmail_query_params>" )
    fileHandle.write ( "    <gmail_query_string>" )
    fileHandle.write ( gmail_query_string )
    fileHandle.write ( "    </gmail_query_string>" )
    fileHandle.write ( "</gmail_query_params>" )
    for thread in messages:
        #if len(thread) == 1:
        if thread:
            d = {'id': thread.id, 'subject': thread.subject.encode("utf-7")}
            #print '<p>%s</p>' % (link % d)
            #addLabels(thread,"zTest.1, zTest.2, zTest.3")
            linkTxt = '''<link>__link__</link>'''.replace('__link__',link)
            linkTxt = linkTxt.replace('<a href="','')
            linkTxt = linkTxt.replace('</a>','')
            #print thread.subject.encode("utf-8")
            #print mess_by_id_link.replace('__id__', thread.id)
            
            fileHandle.write ( "<message>" )
            
            messField = '''   <message_id>__id__</message_id>'''.replace('__id__',thread.id)
            fileHandle.write ( messField )
            messField = '''   <subject>__subject__</subject>'''.replace('__subject__',thread.subject.encode("utf-8"))
            fileHandle.write ( messField )
            #messField = '''   <authors>__authors__</authors>'''.replace('__authors__',thread.authors)
            #fileHandle.write ( messField )

            fileHandle.write ( "</message>" )


    fileHandle.write ( "</gmail_query>" )
    fileHandle.close()
    if gm.loggedIn():
        if gm.storeFile('c:\qq.txt', 'zTest.3'):
            print 'stored'
    else:
        print gm.errorMessage()
